import pymongo
from pymongo import ReturnDocument
from bs4 import BeautifulSoup
import requests
import random
from retry import retry
# 设置代理
proxies = {
    'http': 'http://127.0.0.1:15732',
    'https': 'http://127.0.0.1:15732'
}
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36"}
def get_proxies():
    port = random.randint(24000, 24400)
    proxies = {'http':f'http://zheng123:zheng123@haproxy.iinti.cn:{port}',
               'https':f'http://zheng123:zheng123@haproxy.iinti.cn:{port}'}
    return proxies
USER_AGENT_LIST=[
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1",
    "Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6",
    "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6",
    "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1",
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5",
    "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
    "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SE 2.X MetaSr 1.0; SE 2.X MetaSr 1.0; .NET CLR 2.0.50727; SE 2.X MetaSr 1.0)",
    "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
    "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
    "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3",
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24",
    "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24"
]

headers ={
    "User-Agent":random.choice(USER_AGENT_LIST)}

def get_html(url):
    try:
        html = requests.get(url,headers=headers,proxies=get_proxies(),timeout=5)#超时设置为3秒
    except Exception as e:
        for i in range(2):  # 循环2次去请求网站
            html = requests.get(url,headers=headers,proxies=get_proxies(),timeout=10)
    soup = BeautifulSoup(html.text,"lxml")
    return soup
# 修改为自己的mongodb
host="127.0.0.1"

class mongo_manager():
    def __init__(self, collect_name,db):
        self.client=pymongo.MongoClient(host=host, port=27017)
        # username="root",password="123456"
        self.db=self.client[db]
        self.collect=self.db[collect_name]

    def find_one_and_update(self,query,update,sort,projection=None,):
        return  self.collect.find_one_and_update(query,{'$set': update},return_document=ReturnDocument.AFTER,sort=sort,projection=projection)

    def find_one_and_update(self, filter, update_data):
        # pymongo.ReturnDocument.AFTER 表示 返回修改后的文档
        result = self.collect.find_one_and_update(filter=filter, update={'$set': update_data},
                                                  # sort=[("articles_count", -1)],
                                                  return_document=pymongo.ReturnDocument.AFTER)
        return result
    def getCollect(self,collect_name:str)->pymongo.collection.Collection :
        """
        创建集合
        :return:
        """
        if bool(collect_name):
            return self.db[collect_name]
        return  self.collect


    # def findById(self,id:str):
    #     myquery = {"_id": ObjectId(id)}
    #     return self.collect.find_one(myquery)


    def findAll(self,data=None):
        if bool(data):
            return self.collect.find(data)
        return  self.collect.find()

    def findOne(self,data=None):
        if bool(data):
            return self.collect.find_one(data)
        return  self.collect.find_one()

    def insertOne(self,data:dict):
        return self.collect.insert_one(data)

    def insertMany(self,datas:list):
        return self.collect.insert_many(datas)

    def updateOne(self,query,new_value):
        newvalues = {"$set": new_value}
        return self.collect.update_one(query, newvalues)

    def updateMany(self, query, new_value):
        newvalues = {"$set": new_value}
        return self.collect.update_many(query, newvalues)

    # def deleteById(self,id):
    #     return self.collect.remove({"_id", ObjectId(id)})

    def  deleteOne(self,myquery):
        return  self.collect.delete_one(myquery)

    def deleteMany(self,myquery):
        return  self.collect.delete_many(myquery)
    def not_exist(self, query):
        if bool(query):
            data = self.collect.find_one(query)
            if data:
                return False
            return True

    def exist(self, query):
        if bool(query):
            data = self.collect.find_one(query)
            if data:
                return True
            return False
    def close(self):
        self.client.close()